import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Tooltip,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, Select,Calendar,Typography,Badge
} from 'antd';

import find from 'lodash/find';
import OrganizationChart from "@dabeng/react-orgchart";
import debounce from 'lodash/debounce';
import { ellipsis, afterCloseModal, DescriptionItem } from '@/utils/utils';
import BuildModalTitle from '@/components/BuildModalTitle';
import AddOrEditPrice from './AddOrEditPrice';
import styles from './index.less'
import party from './../../images/party_org.png'
const RadioButton = Radio.Button;
const { Text } = Typography;
const RadioGroup = Radio.Group;
const { confirm } = Modal;
@connect(({ party_organizational, loading,global }) => ({
  party_organizational,
  global,
  loading: loading.models.party_organizational,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, { name: 'organization_edit' }),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      btnLoading:false,
      nowDate:moment().format("YYYY-MM-DD")
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      party_organizational: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      // setTimeout(() => {
      //   table.scrollTop = scrollData.y;
      //   table.scrollLeft = scrollData.x;
      // }, 0);

    } else {
      const {
        party_organizational: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'party_organizational/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'party_organizational/changeLoaded',
          });
        },
      });

    }
    window.addEventListener('resize', this.resize);
    // table.addEventListener('scroll', debounce(this.scroll, 150));
  }



  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    return;
    const table = document.querySelector('.ant-table-body');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'party_organizational/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };
  handleEdit=()=>{
    const formValues = this.EditForm.props.form.getFieldsValue();
    console.log('formValues',formValues)
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: 'party_organizational/edit',
      payload: {
        ...formValues,
        id:this.state.editRecord.id
      },
      callback() {
        message.success('修改组织成功');
        that.setState({
          editModal: false,
        });
        const {
          party_organizational: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  }
  selectNode = (nodeData) => {
    console.log('nodeData',nodeData)
    alert("Hi All. I'm " + nodeData.name + ". I'm a " + nodeData.title + ".");
  };
  handleAdd = () => {
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: 'party_organizational/add',
      payload: {
        ...formValues,
        parent_id:this.state.editRecord.id
      },
      callback() {
        message.success('添加下属组织成功');
        that.setState({
          addModal: false,
        });
        const {
          party_organizational: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleDelete = id => {
    const that = this;
    const {dispatch} = this.props;
    dispatch({
      type: 'party_organizational/remove',
      payload: {id},
      callback: ()=> {
        message.success('删除组织成功')
        const {
          party_organizational: {searchParams},
        } = that.props;
        that.handleSearch(searchParams);
      }
    });
  };
  render() {
    const that = this;
    const {
      party_organizational: { data, loading, tableY, meta, searchParams, selectedRowKeys, additional },
      global:{gridTableW}
    } = this.props;
    const ds = {
      id: "n1",
      name: "书记",
      title: "书记",
      children: [
        {
          id: "n11",
          name: "副书记",
          title: "副书记",
          children:[
            {
              id: "n3",
              name: "党小组",
              title: "党小组",
              children: [
                { id: "n4", name: "第一党小组", title: "第一党小组" },
                { id: "n5", name: "第二党小组", title: "第二党小组" },
                { id: "n8", name: "第三党小组", title: "第三党小组r" }
              ]
            },
            { id: "n9", name: "支委成员", title: "支委成员" },
          ]
        }
      ]
    };
    const MyNode = ({ nodeData }) => {
      return (
        <div >
          <div className="position" style={{display:'block',height:'70px'}}><img style={{width:'30px',height:'30px',margin:'5px 0 1px'}} src={party} alt=""/>
          <div>{nodeData.name}</div></div>
{/*          <div className="fullname">{nodeData.name}</div>*/}
          <div>
            {
              this.state.showAddBtn&&<Fragment>
                <Tooltip  title={'添加下属组织'} >
                  <Icon type="plus-square"  style={{cursor:'pointer',marginRight:'3px'}}
                        onClick={()=>{
                          that.setState({
                            editRecord:nodeData,
                            addModal:true,

                          })
                        }}/>
                </Tooltip>
                <Tooltip  title={'修改'}>
                  <Icon title={'修改'} type="form" style={{cursor:'pointer',marginRight:'3px'}}
                        onClick={()=>{
                          that.setState({
                            editRecord:nodeData,
                            editModal:true,

                          })
                        }}/>
                </Tooltip>
                {
                  nodeData.children&& nodeData.children.length===0 && nodeData.parent_id &&
                  <Tooltip  title={'删除该组织'}  >
                    <Icon type="close-square" style={{cursor:'pointer'}}
                          onClick={()=>{
                            console.log('nodeData',nodeData)
                            confirm({
                              title: `确定要删除"${nodeData.name}"?`,
                              content: '删除后数据不可逆，请谨慎操作！',
                              okText: '确定',
                              okType: 'danger',
                              cancelText: '取消',
                              centered:true,
                              maskClosable: true,
                              onOk() {
                                that.handleDelete(nodeData.id);
                              },
                              onCancel() {
                                console.log('Cancel');
                              },
                            });
                          }}/>
                  </Tooltip>
                }
              </Fragment>
            }

            </div>
        </div>
      );
    };
    console.log('data',data)
    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>组织架构</span>
      </div>
      <div className="table-page" style={{padding:'0'}}>
        <OrganizationChart NodeTemplate={MyNode}
                           containerClass={styles.organization}
                           datasource={data}
                           chartClass="myChart"
                           depth={4}

                           // draggable={true}
                           onClickChart={(e)=>{console.log(e)}}
                           pan={true} zoom={true} />
      </div>
      <Modal
        title={<BuildModalTitle visible={this.state.addModal} modalClass="addModal"
                                title={`添加 ${this.state.editRecord.name} 下属组织`}/>}
        destroyOnClose
        visible={this.state.addModal}
        centered
        onOk={this.handleAdd}
        className="addModal"

        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ addModal: false, editRecord: {} });
        }}

      >
        <AddOrEditPrice
          type={'add'}
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.AddForm = inst}
        />

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.editModal} modalClass="editModal"
                                title={`修改 ${this.state.editRecord.name}`}/>}
        destroyOnClose
        visible={this.state.editModal}
        centered
        onOk={this.handleEdit}
        className="editModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ editModal: false, editRecord: {} });
        }}

      >
       <AddOrEditPrice
         type={'edit'}
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.EditForm = inst}
        />

      </Modal>
    </div>;
  }
}

export default BasicList;
